package com.noble.glamour.ui.agora.act.dialog;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.view.menu.MenuBuilder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.faceunity.MRender;
import com.noble.glamour.R;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.popup.OptionMenu;
import com.noble.glamour.module.logic.baseui.popup.OptionMenuView;
import com.noble.glamour.module.logic.baseui.popup.PopupMenuView;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.ui.agora.act.bean.Props;
import com.noble.glamour.ui.user.my.adapter.GiftViewPagerAdapter;
import com.noble.glamour.ui.user.my.view.CustomViewPager;
import com.noble.glamour.ui.user.my.view.PageIndicatorView;
import com.noble.library.log.PToast;
import com.noble.library.utils.ScreenUtils;
import com.noble.library.view.base.BaseDialogFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * FaceU道具弹框
 * <p>
 * Created by Su on 2017/7/19.
 */
public class RtcFaceUnityDialog extends BaseDialogFragment implements RequestComplete, AdapterView.OnItemClickListener, View.OnClickListener, OptionMenuView.OnOptionMenuClickListener, ViewPager.OnPageChangeListener {
    private static final int FACE_USER_MY = 0;      // faceU自己使用
    private static final int FACE_USER_OTHER = 1;   // faceU对方使用

    private RelativeLayout faceChoose;
    private PopupMenuView popup;
    private PageIndicatorView pageIndicatorView;
    private CustomViewPager vpViews;
    private List<GridView> mLists;
    private TextView tvUser;        // faceU使用方

    private int pageCount;          // 总页数
    private int onePageCount = 0;   // 每页数量
    private int curPage = 0;        // 当前页
    private int position = -1;      // 当前选中item
    private View oldView = null;    // 前一个选中item
    private int faceUser = FACE_USER_MY;  // faceU使用方，默认给自己使用

    // 道具列表
    private List<Props> propsList = new ArrayList<>();

    public RtcFaceUnityDialog() {
        settWindowAnimations(R.style.AnimDownInDownOutOverShoot);
        setGravity(Gravity.BOTTOM);
        setDialogSizeRatio(1, 0);
        setCancelable(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.f1_video_faceu_dialog);
        initView();
        return getContentView();
    }

    private void initView() {
        initPropList();
        onePageCount = ((ScreenUtils.getScreenWidth(getContext()) - ScreenUtils.dp2px(getContext(), 10)) / ScreenUtils.dp2px(getContext(), 84)) * 2;//根据屏幕宽度计算列数
        TextView diamond = (TextView) findViewById(R.id.my_diamond);
        faceChoose = (RelativeLayout) findViewById(R.id.face_choose);
        tvUser = (TextView) findViewById(R.id.face_user);

        //设置page dot背景
        pageIndicatorView = (PageIndicatorView) findViewById(R.id.face_indicator);
        pageIndicatorView.setSelectDot(12, 8, R.drawable.p1_dot_select);//选中
        pageIndicatorView.setUnselectDot(8, 8, R.drawable.p1_dot_unselect);//未选中

        // ViewPager
        vpViews = (CustomViewPager) findViewById(R.id.face_view_pager);
        vpViews.setRow(2);
        vpViews.addOnPageChangeListener(this);
        initGridView();

        // pop弹框
        popup = new PopupMenuView(getContext(), R.layout.f1_chat_pop_item);
        popup.inflate(R.menu.f1_video_chat_choose, new MenuBuilder(getContext()));
        popup.setOrientation(LinearLayout.VERTICAL);
        popup.setOnMenuClickListener(this);

        faceChoose.setOnClickListener(this);
        Button confirm = (Button) findViewById(R.id.face_confirm);
        confirm.setOnClickListener(this);
        diamond.setText(String.valueOf(ModuleMgr.getCenterMgr().getMyInfo().getDiamand()));
    }

    /**
     * 处理道具数据
     */
    private void initPropList() {
        List<Props> props = ModuleMgr.getRtcEnginMgr().getPropList().getPropsList();
        Props prop = new Props();
        prop.setFirst(true);

        propsList.add(prop);
        propsList.addAll(props);
    }

    private void initGridView() {
        pageCount = (int) Math.ceil(propsList.size() / (float) onePageCount);//计算总页数
        //分页数据处理
        mLists = new ArrayList<>();
        for (int i = 0; i < pageCount; i++) {
            final GridView gv = new GridView(getContext());
            final RtcFaceUnityAdapter gvGift = new RtcFaceUnityAdapter(getContext(), this, propsList, i, onePageCount);
            gv.setAdapter(gvGift);
            gv.setGravity(Gravity.CENTER);
            gv.setClickable(true);
            gv.setFocusable(false);
            gv.setNumColumns(onePageCount / 2);
            gv.setSelector(R.color.transparent);
            gv.setFadingEdgeLength(0);
            mLists.add(gv);
        }

        // 设置到布局
        GiftViewPagerAdapter gvpAdapter = new GiftViewPagerAdapter(getContext(), mLists);
        vpViews.setAdapter(gvpAdapter);
        pageIndicatorView.initIndicator(pageCount);
        if (pageCount > 1)
            pageIndicatorView.setSelectedPage(0);
    }

    private void submit() {
        // 未选择道具
        if (position == -1) {
            PToast.showShort(App.activity.getString(R.string.chat_face_no_choose));
            return;
        }

        // 对方版本过低
        if (faceUser == FACE_USER_OTHER && ModuleMgr.getRtcEnginMgr().getEngineConfig().msgVer < 28) {
            PToast.showShort(App.activity.getString(R.string.chat_face_u_version));
            return;
        }

        // 对方未开启摄像头
        if (faceUser == FACE_USER_OTHER && !ModuleMgr.getRtcEnginMgr().getEngineConfig().mOpenCamera) {
            PToast.showShort(App.activity.getString(R.string.chat_face_no_use_other));
            return;
        }

        // 给自己使用
        if (faceUser == FACE_USER_MY) {
            // 男性不看自己
            if (ModuleMgr.getCenterMgr().getMyInfo().isMan()
                    && ModuleMgr.getRtcEnginMgr().getEngineConfig().mCamera == 2)
                PToast.showShort(App.activity.getString(R.string.chat_face_no_use_self));
            else
                MRender.setCurrentItemByPosition(position);
            return;
        }

        // 给他人使用: 还原传id=0
        ModuleMgr.getRtcEnginMgr().reqUsingProp(propsList.get(position).getId(), faceUser, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.face_choose:
                popup.show(faceChoose);
                break;

            case R.id.face_confirm:
                submit();
                dismiss();
                break;

        }
    }

    @Override
    public boolean onOptionMenuClick(int position, OptionMenu menu) {
        if (menu.getId() == R.id.face_user_my) {
            faceUser = FACE_USER_MY;
            tvUser.setText(App.activity.getString(R.string.chat_face_user_my));
        }

        if (menu.getId() == R.id.face_user_other) {
            faceUser = FACE_USER_OTHER;
            tvUser.setText(App.activity.getString(R.string.chat_face_user_other));
        }
        return true;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        curPage = position;
        pageIndicatorView.setSelectedPage(curPage);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        this.position = curPage * onePageCount + position;
        View mView = null;
        if (mLists.get(curPage).getAdapter() instanceof RtcFaceUnityAdapter) {
            mView = ((RtcFaceUnityAdapter) (mLists.get(curPage).getAdapter())).getView();
        }
        if (oldView != null && oldView != mView) {
            oldView.setBackgroundResource(R.color.transparent);
            if (mView != null)
                mView.setBackgroundResource(R.drawable.p1_rtc_gift_item_bg);//设置选中背景色
        }
        if (oldView == null && mView != null) {
            mView.setBackgroundResource(R.drawable.p1_rtc_gift_item_bg);//设置选中背景色
        }
        if (this.position < propsList.size()) {
            if (mLists.get(curPage).getAdapter() instanceof RtcFaceUnityAdapter) {
                oldView = mView;
            }
        }
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        if (faceUser == FACE_USER_MY) {
            return;
        }
        if (!response.isOk()) PToast.showShort(response.getMsg());
    }
}
